<template>
  <!-- 选择器 -->
  <view class="picker_container" id="main">
    <!-- 选择框 -->
    <scroll-view
      scroll-y="true"
      class="picker_box"
      :scroll-top="scrollTop"
      @scroll="scroll"
      ref="pickerRef"
      scroll-with-animation="true"
    >
      <!-- 选项 -->
      <view
        class="item"
        v-for="(item, index) of renderColumns"
        :key="index"
        :class="item === selected ? 'current' : ''"
      >
        {{ item }}
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref, watch } from 'vue'

const scrollTop = ref(0) // 设置滚动高度
const selected = ref('') // 选中项
const pickerRef = ref() // 选择器Ref
const itemHeight = ref() // 选项高度

const props = defineProps({
  columns: {
    type: Array,
    default: () => [],
  },
})
const emit = defineEmits(['changSelected'])
const instance = getCurrentInstance()
// 获取picker的高度

onMounted(() => {
  let main = uni.createSelectorQuery().in(instance.proxy)

  main
    .select('.picker_box')
    .boundingClientRect((data) => {
      console.log('获取picker的高度', data)
      itemHeight.value = data.height / 3
      console.log('获取picker的高度', itemHeight.value)
    })
    .exec()
  selected.value = props.columns[0]
})

// 渲染列
const renderColumns = computed(() => {
  if (props.columns.length) {
    const empty = ''
    return [empty, ...props.columns, empty]
  } else {
    return []
  }
})
// 监听列变化
watch(
  () => props.columns.length,
  (newColumns) => {
    if (newColumns && newColumns.length > 0) {
      selected.value = newColumns[0]
      emit('changSelected', selected.value)
    }
  },
  { immediate: true }, // 立即执行一次
)
watch(
  () => selected.value,
  () => {
    console.log('测试', selected.value)
    emit('changSelected', selected.value)
  },
)

const scroll = (ev) => {
  const scroll = ev.detail.scrollTop
  const index = Math.round(scroll / itemHeight.value)
  selected.value = renderColumns.value[index + 1]
  if (scroll / itemHeight.value) {
    scrollTop.value = index * itemHeight.value
  }
}
</script>

<style scoped lang="scss">
// 选择器
.picker_container {
  position: relative;
  width: 100%;
  height: 100%;

  // 选择框
  .picker_box {
    position: absolute;
    left: 0;
    height: 100%;
    width: 100%;
    overflow-y: scroll;
    scroll-behavior: smooth;

    // 隐藏滚动条
    ::-webkit-scrollbar {
      display: none;
    }

    // 选项
    .item {
      height: 33.3%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s;
    }

    // 选中项
    .item + .item {
      color: darkblue;
    }

    // 当前选中项
    .current {
      font-weight: 600;
      font-size: 22px;
      color: darkblue;

      & + .item {
        color: darkblue;
      }
    }
  }
}

hr {
  margin: 40px 0;
}
</style>
